package com.laoxu.test.springboot.dao;

import com.laoxu.test.springboot.model.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author laoxu
 * @Date 2020/8/15 15:16
 **/
@Repository
public class UserDao {
    private static List<User> users = new ArrayList<>();

    static {

        for (int i = 1; i <= 10; i += 1) {
            users.add(new User(i, "张三" + i, "男", i+10));
        }
    }

    //http://www.layui.com/demo/table/user/?page=1&limit=10

    /**
     * 获得所有用户
     */
    public List<User> getPager(int page, int limit) {
        List<User> list = new ArrayList<>();
        int start = (page - 1) * limit;
        for (int i = start; i < start + limit && i < users.size(); i++) {
            list.add(users.get(i));
        }
        return list;
    }

    /**
     * 获得所有用户
     */
    public List<User> getAllUsers() {
        return users;
    }

    /**
     *  根据ID获取用户
     * @param id
     * @return
     */
    public User getById(int id){
        for (User u:
             users) {
            if (u.getId() == id){
                return u;
            }
        }

        return null;
    }

    /**
     * 添加用户
     */
    public void addUser(User user) {
        if (user.getId() <= 0) { // 未设置id
            int index = users.size() - 1; // 获得最后一个用户的索引号
            if (index < 0) { // 如没有一个用户
                user.setId(1); // 编号为1
            } else {
                user.setId(users.get(index).getId() + 1); // 获得最后一个用户的编号+1
            }
        }
        users.add(user);
    }

    /**
     * 删除用户
     */
    public void delUser(int id) {
        User delUser = null;
        for (User user : users) {
            if (user.getId() == id) {
                delUser = user;
                break;
            }
        }
        users.remove(delUser);
    }

    /**
     * 删除用户（多选）
     */
    public void delUsers(int[] ids) {
        User delUser = null;
        for (int i = 0; i < ids.length; i++) {
            for (int j = 0; j < users.size(); j++) {
                if (users.get(j).getId() == ids[i]) {
                    users.remove(j);
                }
            }
        }
    }

    public void updateUser(User obj) {
        User editUser = null;
        for (User user : users) {
            if (user.getId() == obj.getId()) {
                editUser = user;
                break;
            }
        }
        editUser.setName(obj.getName());
        editUser.setGender(obj.getGender());
        editUser.setAge(obj.getAge());
    }
}
